using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 可恢复创作服务
    /// 提供断点续传功能，支持网络中断后恢复创作
    /// </summary>
    public class ResumableCreationService
    {
        private readonly ILogger<ResumableCreationService> _logger;
        private readonly NetworkRecoveryService _networkRecovery;
        private readonly IAIService _aiService;

        public ResumableCreationService(
            ILogger<ResumableCreationService> logger,
            NetworkRecoveryService networkRecovery,
            IAIService aiService)
        {
            _logger = logger;
            _networkRecovery = networkRecovery;
            _aiService = aiService;
        }

        /// <summary>
        /// 创作任务状态
        /// </summary>
        public class CreationTaskState
        {
            public string TaskId { get; set; } = string.Empty;
            public string TaskType { get; set; } = string.Empty;
            public string ProjectPath { get; set; } = string.Empty;
            public DateTime StartTime { get; set; }
            public DateTime LastUpdateTime { get; set; }
            public int TotalSteps { get; set; }
            public int CompletedSteps { get; set; }
            public Dictionary<string, object> TaskData { get; set; } = new();
            public List<string> CompletedItems { get; set; } = new();
            public List<string> FailedItems { get; set; } = new();
            public string? LastError { get; set; }
            public bool IsCompleted { get; set; }
            public bool IsCancelled { get; set; }
        }

        /// <summary>
        /// 创作任务结果
        /// </summary>
        public class CreationTaskResult
        {
            public bool IsSuccess { get; set; }
            public string Message { get; set; } = string.Empty;
            public object? Data { get; set; }
            public string? ErrorDetails { get; set; }
            public bool WasResumed { get; set; }
            public int TotalRetries { get; set; }
        }

        /// <summary>
        /// 执行可恢复的创作任务
        /// </summary>
        public async Task<CreationTaskResult> ExecuteResumableTaskAsync<T>(
            string taskId,
            string taskType,
            string projectPath,
            Func<CreationTaskState, IProgress<int>?, CancellationToken, Task<T>> taskFunction,
            IProgress<int>? progressCallback = null,
            CancellationToken cancellationToken = default)
        {
            var result = new CreationTaskResult();
            var totalRetries = 0;

            try
            {
                // 尝试加载现有任务状态
                var taskState = await LoadTaskStateAsync(taskId, projectPath);
                var wasResumed = taskState != null;

                if (taskState == null)
                {
                    // 创建新任务状态
                    taskState = new CreationTaskState
                    {
                        TaskId = taskId,
                        TaskType = taskType,
                        ProjectPath = projectPath,
                        StartTime = DateTime.Now,
                        LastUpdateTime = DateTime.Now
                    };
                }
                else
                {
                    _logger.LogInformation($"恢复任务: {taskId}, 已完成步骤: {taskState.CompletedSteps}/{taskState.TotalSteps}");
                    result.WasResumed = true;
                }

                // 执行任务，支持网络重试
                var taskResult = await _networkRecovery.ExecuteWithNetworkRetryAsync(
                    async () =>
                    {
                        totalRetries++;
                        taskState.LastUpdateTime = DateTime.Now;
                        await SaveTaskStateAsync(taskState);

                        return await taskFunction(taskState, progressCallback, cancellationToken);
                    },
                    maxRetries: 5,
                    networkRecoveryTimeout: TimeSpan.FromMinutes(15),
                    cancellationToken);

                // 任务完成，标记状态
                taskState.IsCompleted = true;
                taskState.LastUpdateTime = DateTime.Now;
                await SaveTaskStateAsync(taskState);

                result.IsSuccess = true;
                result.Message = wasResumed ? "任务恢复并完成" : "任务完成";
                result.Data = taskResult;
                result.TotalRetries = totalRetries - 1; // 减去初始执行

                _logger.LogInformation($"任务 {taskId} 完成，重试次数: {result.TotalRetries}");
            }
            catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
            {
                // 保存取消状态
                var taskState = await LoadTaskStateAsync(taskId, projectPath);
                if (taskState != null)
                {
                    taskState.IsCancelled = true;
                    taskState.LastUpdateTime = DateTime.Now;
                    await SaveTaskStateAsync(taskState);
                }

                result.IsSuccess = false;
                result.Message = "任务已取消";
                _logger.LogInformation($"任务 {taskId} 被用户取消");
            }
            catch (Exception ex)
            {
                // 保存错误状态
                var taskState = await LoadTaskStateAsync(taskId, projectPath);
                if (taskState != null)
                {
                    taskState.LastError = ex.Message;
                    taskState.LastUpdateTime = DateTime.Now;
                    await SaveTaskStateAsync(taskState);
                }

                result.IsSuccess = false;
                result.Message = "任务执行失败";
                result.ErrorDetails = ex.Message;
                result.TotalRetries = totalRetries - 1;

                _logger.LogError(ex, $"任务 {taskId} 执行失败，重试次数: {result.TotalRetries}");
            }

            return result;
        }

        /// <summary>
        /// 保存任务状态
        /// </summary>
        public async Task SaveTaskStateAsync(CreationTaskState taskState)
        {
            try
            {
                var stateDir = Path.Combine(taskState.ProjectPath, ".creation_states");
                Directory.CreateDirectory(stateDir);

                var stateFile = Path.Combine(stateDir, $"{taskState.TaskId}.json");
                var json = JsonSerializer.Serialize(taskState, new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                await File.WriteAllTextAsync(stateFile, json);
                _logger.LogDebug($"任务状态已保存: {stateFile}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存任务状态失败: {taskState.TaskId}");
            }
        }

        /// <summary>
        /// 加载任务状态
        /// </summary>
        public async Task<CreationTaskState?> LoadTaskStateAsync(string taskId, string projectPath)
        {
            try
            {
                var stateFile = Path.Combine(projectPath, ".creation_states", $"{taskId}.json");
                if (!File.Exists(stateFile))
                {
                    return null;
                }

                var json = await File.ReadAllTextAsync(stateFile);
                var taskState = JsonSerializer.Deserialize<CreationTaskState>(json);

                _logger.LogDebug($"任务状态已加载: {stateFile}");
                return taskState;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载任务状态失败: {taskId}");
                return null;
            }
        }

        /// <summary>
        /// 清理已完成的任务状态
        /// </summary>
        public async Task CleanupCompletedTasksAsync(string projectPath, TimeSpan? olderThan = null)
        {
            try
            {
                var stateDir = Path.Combine(projectPath, ".creation_states");
                if (!Directory.Exists(stateDir))
                {
                    return;
                }

                var cutoffTime = DateTime.Now - (olderThan ?? TimeSpan.FromDays(7));
                var stateFiles = Directory.GetFiles(stateDir, "*.json");

                foreach (var stateFile in stateFiles)
                {
                    try
                    {
                        var json = await File.ReadAllTextAsync(stateFile);
                        var taskState = JsonSerializer.Deserialize<CreationTaskState>(json);

                        if (taskState != null && 
                            (taskState.IsCompleted || taskState.IsCancelled) &&
                            taskState.LastUpdateTime < cutoffTime)
                        {
                            File.Delete(stateFile);
                            _logger.LogDebug($"已清理过期任务状态: {stateFile}");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, $"清理任务状态文件失败: {stateFile}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理任务状态失败");
            }
        }

        /// <summary>
        /// 获取项目中的所有任务状态
        /// </summary>
        public async Task<List<CreationTaskState>> GetProjectTaskStatesAsync(string projectPath)
        {
            var taskStates = new List<CreationTaskState>();

            try
            {
                var stateDir = Path.Combine(projectPath, ".creation_states");
                if (!Directory.Exists(stateDir))
                {
                    return taskStates;
                }

                var stateFiles = Directory.GetFiles(stateDir, "*.json");
                foreach (var stateFile in stateFiles)
                {
                    try
                    {
                        var json = await File.ReadAllTextAsync(stateFile);
                        var taskState = JsonSerializer.Deserialize<CreationTaskState>(json);
                        if (taskState != null)
                        {
                            taskStates.Add(taskState);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, $"读取任务状态文件失败: {stateFile}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取项目任务状态失败");
            }

            return taskStates;
        }
    }
}
